﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace MSA.SocialNetworking
{
    class CallURL
    {
        public string SendRequest(string _URL, CredentialCache _creds, string _method, string _message)
        {
            string response = String.Empty;
            //if (_method == "GET" && _message != "")
            //{
            //    _URL = string.Format("{0}/?{1}", _URL, _message);
            //}
            try
            {
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(_URL);
                wReq.Method = _method;
                wReq.Credentials = _creds;
                wReq.Timeout = 100000;
                wReq.ServicePoint.Expect100Continue = false;
                if (_method == "POST")
                {
                    wReq.ContentType = "application/x-www-form-urlencoded";
                    byte[] bytes = Encoding.ASCII.GetBytes(_message);
                    wReq.ContentLength = bytes.Length;
                    using (Stream str = wReq.GetRequestStream())
                    {
                        str.Write(bytes, 0, bytes.Length);
                        str.Close();
                    }
                }
                using (WebResponse wResp = wReq.GetResponse())
                {
                    using (StreamReader reader = new StreamReader(wResp.GetResponseStream()))
                    {
                        response = reader.ReadToEnd();
                    }
                    wReq = null;
                    wResp.Close();
                }
                wReq = null;
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.ProtocolError)
                {
                    response = "Error";
                    throw new WebException(((int)((HttpWebResponse)e.Response).StatusCode).ToString());
                }
            }
            catch (Exception e)
            {
                response = "Error";
                throw e;
            }
            return response;
        }
    }
}
